package com.example.oj.commondUtil;

import org.springframework.context.annotation.Configuration;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Configuration
public class CreateChildProcess {
    public static int run(String cmd, String stdoutFile, String stderrFile) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (stdoutFile != null) {
            try (InputStream stdoutFrom = process.getInputStream();
                 OutputStream stdoutTo = new FileOutputStream(stdoutFile)) {
                while (true) {
                    byte[] bytes = new byte[4096];
                    int len = stdoutFrom.read(bytes);
                    if (len == -1) {
                        break;
                    }
                    stdoutTo.write(bytes, 0, len);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        if (stderrFile != null) {
            try (InputStream stderrFrom = process.getErrorStream();
                 OutputStream stderrTo = new FileOutputStream(stderrFile)) {
                while (true) {
                    byte[] bytes = new byte[4096];
                    int len = stderrFrom.read(bytes);
                    if (len == -1) {
                        break;
                    }
                    stderrTo.write(bytes, 0, len);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        try {
            return process.waitFor();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
